package com.qingxin.ui.bean;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.digester.Substitutor;
import org.xml.sax.Attributes;

/**
 * 内容转换器，将配置的内容转换为实际值
 */
public class UITextSubstitutor extends Substitutor {
	
	private UIDynamicReplacer dynamicReplacer;
	private final Matcher matcher;
	
	public UITextSubstitutor(UIDynamicReplacer dynamicReplacer) {
		this.dynamicReplacer = dynamicReplacer;
		matcher = Pattern.compile("(?:(__dyc):(\\w+))").matcher("");
	}
	
	
	/**
	 * 转换属性
	 * 
	 * @param attributes
	 * @return
	 */
	@Override
	public Attributes substitute(Attributes attributes) {
		return attributes;
	}

	
	/**
	 * 转换标签内容
	 * 
	 * @param bodyText
	 * @return
	 */
	@Override
	public String substitute(String bodyText) {
		if(dynamicReplacer != null && bodyText != null && bodyText.length()>0){
			StringBuffer buf = new StringBuffer();
			matcher.reset(bodyText);
			while(matcher.find()){
				bodyText = matcher.group(2);
				bodyText = dynamicReplacer.replace(bodyText);
				matcher.appendReplacement(buf, Matcher.quoteReplacement(bodyText));
			}
			matcher.appendTail(buf);
			bodyText = buf.toString();
		}
		
		return bodyText;
	}
	
}
